import { formatDateTime } from './utils'
import dividend_list from './dividend_list'
// 录入业绩记录
function insertPerformanceRecord(
  dealerId,
  dealerName,
  performanceDate,
  teamMoney,
  selfMoney,
  sqlite
) {
  return new Promise((resolve, reject) => {
    const sql =
      'INSERT INTO performance_record(dealer_id,dealer_name,performance_date,team_money,self_money,create_time,modify_time) VALUES (?, ?, ?, ?, ?, ?, ?)'
    sqlite.run(
      sql,
      [
        dealerId,
        dealerName,
        performanceDate,
        teamMoney,
        selfMoney,
        formatDateTime(),
        formatDateTime()
      ],
      function (err) {
        if (err) {
          console.error('Error inserting performance_record:', err.message)
          reject(err.message)
        } else {
          resolve(this.lastID)
        }
      }
    )
  })
}
// 获取业绩记录
function getPerformanceRecord(dealerId, performanceDate, sqlite) {
  return new Promise((resolve, reject) => {
    const dataSql = `SELECT * FROM performance_record WHERE dealer_id= ? AND  performance_date = ? `
    sqlite.all(dataSql, [dealerId, performanceDate], (err, row) => {
      if (err) {
        console.error('Error getPerformanceRecord:', err.message)
        reject(err.message)
      } else {
        resolve(row)
      }
    })
  })
}
// 修改业绩记录
function updatePerformanceRecord(teamMoney, selfMoney, performanceRecordId, sqlite) {
  return new Promise((resolve, reject) => {
    const sql =
      ' UPDATE performance_record SET team_money = ?,self_money  = ?,modify_time = ? WHERE performance_record_id = ? '
    sqlite.run(sql, [teamMoney, selfMoney, formatDateTime(), performanceRecordId], function (err) {
      if (err) {
        console.error('Error inserting updatePerformanceRecord:', err.message)
        reject(err.message)
      } else {
        resolve(performanceRecordId)
      }
    })
  })
}

// 新增业绩记录方法
export async function handleAddPerformanceRecord(
  dealerId,
  dealerName,
  performanceDate,
  selfMoney,
  sqlite,
  isAutoUpdateFather
) {
  try {
    // 获取经销商某天团队业绩
    const teamMoneyRes = await dividend_list(sqlite).getDealerTeamPerformance(
      dealerId,
      performanceDate
    )
    const teamMoney = teamMoneyRes?.rows?.money || 0 // 确保 teamMoney 有默认值

    // 判断该日期记录表中该经销商是否已有数据
    const existingRecords = await getPerformanceRecord(dealerId, performanceDate, sqlite)

    if (existingRecords.length > 0) {
      // 如果存在记录，更新记录

      const existingRecord = existingRecords[0]
      // 如果是自动更新父级的记录则不相加
      const updatedSelfMoney = isAutoUpdateFather
        ? selfMoney
        : existingRecord.self_money + selfMoney

      const updateResult = await updatePerformanceRecord(
        teamMoney,
        updatedSelfMoney,
        existingRecord.performance_record_id,
        sqlite
      )
      return updateResult // 更新结果返回
    } else {
      // 如果不存在记录，新增记录
      const insertResult = await insertPerformanceRecord(
        dealerId,
        dealerName,
        performanceDate,
        teamMoney,
        selfMoney,
        sqlite
      )
      return insertResult // 插入结果返回
    }
  } catch (error) {
    console.error('Error in handleAddPerformanceRecord:', error.message)
    throw new Error('Failed to add or update performance record')
  }
}

// 获取进销商某天的业绩
function getDealerPerformanceByDate(dealerId, performanceDate, sqlite) {
  return new Promise((resolve, reject) => {
    const dataSql = `SELECT performance_money FROM performance WHERE dealer_id= ? AND  performance_date = ? `
    sqlite.all(dataSql, [dealerId, performanceDate], (err, row) => {
      if (err) {
        console.error('Error getPerformance:', err.message)
        reject(err.message)
      } else {
        if (row.length > 0) {
          resolve(row[0].performance_money)
        } else {
          resolve(0)
        }
      }
    })
  })
}
// 获取所有的父级（不包含自身）
function getParentDealers(dealerId, sqlite) {
  return new Promise((resolve, reject) => {
    const sql = `
      WITH RECURSIVE ParentHierarchy AS (
        -- 起始条件：从指定的经销商开始
        SELECT 
          dealer_id,
          parent_dealer_id,
          dealer_name
        FROM dealer
        WHERE dealer_id = ?

        UNION ALL

        -- 递归条件：查找父级经销商
        SELECT 
          d.dealer_id,
          d.parent_dealer_id,
          d.dealer_name
        FROM dealer d
        INNER JOIN ParentHierarchy ph
        ON d.dealer_id = ph.parent_dealer_id
      )
      SELECT * 
      FROM ParentHierarchy
      WHERE dealer_id != ?; -- 排除自身
    `
    sqlite.all(sql, [dealerId, dealerId], (err, rows) => {
      if (err) {
        console.error('Error fetching parent dealers:', err.message)
        reject(err.message)
      } else {
        resolve(rows) // 返回所有父级经销商（不包含自身）
      }
    })
  })
}

//更新进销商所有父级的业绩记录
export async function handleUpdateParentPerformanceRecord(dealerId, performanceDate, sqlite) {
  // 查找所有的父级
  const pArr = await getParentDealers(dealerId, sqlite)
  // console.log('pArr', pArr)

  const promises = pArr.map(async (item) => {
    const m = await getDealerPerformanceByDate(item.dealer_id, performanceDate, sqlite)
    await handleAddPerformanceRecord(item.dealer_id, item.dealer_name, performanceDate, m, sqlite,true)
  })
  const res = await await Promise.all(promises)
  return res
}

// 业绩记录
export default function (sqlite) {
  return {
    // 获取业绩记录
    getPerformanceRecord(dealerId, performanceDate) {
      return new Promise((resolve, reject) => {
        const dataSql = `SELECT * FROM performance_record WHERE dealer_id= ? AND  performance_date = ? `
        sqlite.all(dataSql, [dealerId, performanceDate], (err, row) => {
          if (err) {
            console.error('Error getPerformanceRecord:', err.message)
            reject(err.message)
          } else {
            resolve(row)
          }
        })
      })
    },

    // 获取某经销商某段时间内的业绩记录
    getPerformanceRecordByDealerForDate(dealerId, startDate, endDate) {
      return new Promise((resolve, reject) => {
        // 动态构造 SQL 查询条件
        let sql = `
          SELECT *
          FROM performance_record
          WHERE dealer_id = ?
        `
        const params = [dealerId]

        // 如果提供了 startDate，添加条件
        if (startDate) {
          sql += ` AND performance_date >= ?`
          params.push(startDate)
        }

        // 如果提供了 endDate，添加条件
        if (endDate) {
          sql += ` AND performance_date <= ?`
          params.push(endDate)
        }

        // 按日期升序排序
        sql += ` ORDER BY performance_date ASC`

        // 执行查询
        sqlite.all(sql, params, (err, rows) => {
          if (err) {
            console.error('Error fetching performance records:', err.message)
            reject('Error fetching performance records')
          } else {
            resolve(rows) // 返回查询结果
          }
        })
      })
    }
  }
}
